// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()

function dateFormat(date) {
  return date.toJSON().substr(0, 19).replace('T', ' ');;
}

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext();
  const { nickName, avatarUrl } = event.userInfo;
  const curDate = dateFormat(new Date(Date.now() + 8 * 60 * 60 * 1000));
  
  try {
    let res = await db.collection('drawBoards').add({
      data: {
        owner: {
          openId: OPENID,
          nickName,
          avatarUrl,
        },
        title: '无标题画板',
        createDate: curDate,
        updateDate: curDate,
        members: {
          [OPENID]: {
            nickName,
            avatarUrl,
            auth: 'edit'
          }
        },
        operates: [],
        version: 0, // 版本号
        imgId: '', // 图片 id
      }
    });
    return {
      code: 0,
      msg: 'success',
      data: {
        drawBoardId: res._id
      }
    }
  } catch(err) {
    return {
      code: 1,
      msg: err,
      data: {}
    }
  }
}